from mcp.server.fastmcp import FastMCP, Context
import asyncio
from mcp.types import RequestParams, SamplingMessage, TextContent

mcp: FastMCP = FastMCP("resource template demo")

# @mcp.tool()
async def log_tool(files: list[str], ctx: Context):
    """
    1.处理文件的日志输出接口
    :param files: 文件列表
    :param ctx: 上下文对象，无需客户端传递
    :return: 处理结果
    """
    for file, index in enumerate(files):
        await asyncio.sleep(1)
        # ctx.log级别的日志可以定义是info、还是debug等等，ctx.info是直接发送info级别的日志
        await ctx.info(f"正在处理第{index}个文件")
    return "所有文件处理完成"

# @mcp.tool()
async def long_task(files: list[str], ctx: Context) -> str:
    """Process multiple files with progress tracking"""
    for index, file in enumerate(files):
        # 模拟处理过程中的延迟
        await asyncio.sleep(1)
        # 设置token
        ctx.request_context.meta = RequestParams.Meta(progressToken=ctx.request_id)
        await ctx.report_progress(progress=(index+1), total=len(files))
    return "处理完成"

@mcp.tool()
async def sampling_tool(ctx: Context) -> str:
    """直接发送一个sampling信息"""
    try:
        response = await ctx.session.create_message(messages=[SamplingMessage(role="user", content=TextContent(
            text="请帮我按照主题“知了课堂上新了MCP课程”为主题写两篇新闻。", type="text"))], max_tokens=2048)
        print(f"response: {response}")
        return "采样成功"
    except Exception as e:
        print(e)
        return "采样失败"

if __name__ == '__main__':
    mcp.run(transport="sse")